<template>
	<div class="container">
		<div class="login-wraper">
			<h2>后台管理系统</h2>

			<el-form :model="user" :rules="rules" ref="loginRef" status-icon>
				<el-form-item prop="username">
					<el-input v-model="user.username">
						<template #prefix>
							<el-icon><User /></el-icon>
						</template>
					</el-input>
				</el-form-item>

				<el-form-item prop="password">
					<el-input v-model="user.password">
						<template #prefix>
							<el-icon><Lock /></el-icon>
						</template>
					</el-input>
				</el-form-item>

				<el-form-item>
					<el-button type="primary" @click="onLogin">登录</el-button>
				</el-form-item>
			</el-form>
		</div>
	</div>
</template>

<script>
import { User, Lock } from '@element-plus/icons-vue'
import { RequestLogin,RequestMenu } from '@/api/index.js'
import sha256 from 'js-sha256'
export default {
	components: {
		User,
		Lock,
	},
	data() {
		return {
			user: {
				username: 'test1',
				password: '123',
			},
			// 定义验证规则
			rules: {
				username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
				password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
			},
		}
	},
	methods: {
		onLogin() {
			// valid参数表示是否验证通过，如果验证没通过，触发验证规则rules
			this.$refs.loginRef.validate(valid => {
				if (valid) {
					this.onRequestLogin()
				}
			})
		},
		async onRequestLogin() {
			let { username, password } = this.user
			password = sha256(password)
			let data = await RequestLogin(username, password)
			
			let { resultCode, resultInfo, token } = data
			if (resultCode == 1) {
	
				// 2. 保存用户信息
				let { username, nick, headerimg,role_id } = resultInfo
				this.$store.dispatch('user/saveUser', { username, nick, headerimg })
				// 2.1 获取动态菜单
				let menuData = await RequestMenu(role_id)
				this.$store.dispatch('menu/saveMenu', menuData.sysmenu)
				// 3. 保存token
				localStorage.setItem('TOKEN', token)
				// 4. 跳转
				this.$router.push({ path: '/home' })
			} else {
				ElMessage({
					message: '用户名或密码出错!',
					type: 'warning',
				})
			}
		},
	},
}
</script>
<style scoped lang="scss">
.container {
	position: absolute;
	width: 100%;
	height: 100%;
	top: 0;
	left: 0;
	background-color: #2b3c4d;
	.login-wraper {
		width: 400px;
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		text-align: center;
		h2 {
			color: white;
		}
		form {
			background-color: white;
			border-radius: 8px;
			padding: 30px 25px;
			.el-button {
				width: 100%;
				margin-top: 24px;
			}
		}
	}
}
</style>
